import React, { Component } from 'react'
import { Card, Table, Modal, Button, message } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { PAGE_SIZE } from '../../utils/constants'
import { formatDate } from '../../utils/dateUtils'
import UserForm from './UserForm'
import { 
  APIGetUserList, 
  APIDeleteUser, 
  APIAddUser, 
  APIUpdateUser 
} from '../../api'


export default class User extends Component {

  state = {
    users: [],
    currentUser: {},
    roles: [],
    isShow: false
  }

  // 添加或修改用户
  addAddOrUpdateUser = async () => {
    if(this.userInfo) {
      if(this.userInfo.password) {
        const result = await APIAddUser(this.userInfo)
        if(result.status === 0) {
          this.getUserList()
          message.success('添加用户成功')
        } else {
          message.error('添加用户失败')
        }
      } else {
        this.userInfo._id = this.state.currentUser._id
        const result = await APIUpdateUser(this.userInfo)
        if(result.status === 0) {
          this.getUserList()
          message.success('修改用户信息成功')
        } else {
          message.error('修改用户信息失败')
        }
      }
    }

    this.setState({
      isShow: false
    })
  }

  // 获取用户列表
  getUserList = async () => {
    const result = await APIGetUserList()
    if(result.status === 0) {
      const { users, roles } = result.data
      this.initRoleNames(roles)
      this.setState({
        users,
        roles
      })
    }
  }

  // 初始化角色列表(根据roles数组生成包含所有角色名的对象，属性名用角色id值)
  initRoleNames = (roles) => {
    const roleNames = roles.reduce((pre, role) => {
      pre[role._id] = role.name
      return pre
    }, {})
    // 保存
    this.roleNames = roleNames
  }

  // 删除指定用户
  deteleUser = (user) => {
    Modal.confirm({
      title: `确认删除${user.username}用户嘛？`,
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        const result = await APIDeleteUser(user._id)
        if(result.status === 0) {
          message.success('删除用户信息成功！')
          this.getUserList()
        } else {
          message.error('删除用户信息失败！')
        }
      }
    })
  }

  // 初始化表格头
  initColums = () => {
    this.columns = [
      {
        title: '用户名',
        dataIndex: 'username'
      },
      {
        title: '邮箱',
        dataIndex: 'email'
      },
      {
        title: '电话',
        dataIndex: 'phone'
      },
      {
        title: '注册时间',
        dataIndex: 'create_time',
        render: formatDate
      },
      {
        title: '所属角色',
        dataIndex: 'role_id',
        render: (role_id) => this.roleNames[role_id]
      },
      {
        title: '操作',
        render: (user) => (
          <span>
            <Button type="link" onClick={() => {
              this.setState({
                isShow: true,
                currentUser: user
              })
            }}>修改</Button>
            <Button type="link" onClick={() => this.deteleUser(user)}>删除</Button>
          </span>
        )
      }
    ]
  }

  componentDidMount() {
    this.getUserList()
  }

  render() {
    const { users, isShow, roles, currentUser } = this.state

    this.initColums()
    const title = (
      <Button 
        type="primary" 
        onClick={() => {
          this.setState({
            isShow: true,
            currentUser: {}
          })
        }}
      >
        创建用户
      </Button>
    )
    return (
      <div>
        <Card title={title}>
          <Table 
            rowKey='_id'
            bordered
            dataSource={users} 
            columns={this.columns}
            pagination={{defaultPageSize: PAGE_SIZE, showQuickJumper: true}}
          />
        </Card>
        <Modal 
          key={Date.now()}
          title={currentUser._id ? "修改用户" : "添加用户"}
          visible={isShow} 
          onOk={this.addAddOrUpdateUser} 
          onCancel={() => this.setState({isShow: false})}
        >
          <UserForm 
            setForm={userInfo => this.userInfo = userInfo}
            user={currentUser} 
            roles={roles}
          />
        </Modal>
      </div>
    )
  }
}
